/**
 * author:Administrator
 * date:2015/8/17
 * desc:日志流,实际上不仅仅是日志，还包含一些逻辑处理，处理完毕后，丢给redis,(logstash 进行日志收集)
 */
"use strict";
var F = require('../function.js');
var rtPoi = new require('./mongo/RtPoi.js')();
var initFun = require('./init.js').initFun;
var articleDao = require('./es/ArticleDao.js');
var debugLog = require('../../o2o/common/function.js').debugLog;

var redisClientDb1 = F.redisClientDb1;
var __key = 'logstash:article';

function Logstash() {
  return this instanceof Logstash ? this : new Logstash();
}
module.exports = new Logstash();
/**
 * 帖子相关 每个帖子都有一个圈子(大类),和小类(圈子细分)
 * @param json
 *
 * post时 uid, vest, tid, action, articleContent,cid,[ ctype, cid2, timeline, lastpost, views, liketimes,status,replies,userreplies ]
 * view时 uid, tid, action, vid
 * reply时 uid, tid, action, vid
 * like时 uid, tid, action, vid
 * edit时 uid, tid, action, articleContent, timeline
 * delete时 uid,tid, action, vid
 * //
 uid 用户id
 vest 是否马甲
 vid 马甲id
 tid 主帖id
 action = post/view/reply/like/edit/delete
 articleConten 主贴内容
 cid 圈子id
 cid2 细分种类
 timeline 帖子发表时间
 lastpost 最后回复时间
 views 查看次数
 liketimes 点赞次数
 status 状态
 replies 回帖次数
 userreplies 用户回帖数
 */
Logstash.prototype.article = function (json) {
  try {
    debugLog(' [debug] logAnalyze_match_old ' + JSON.stringify(json));


    //initFun();
    //var checkResult = __checkInput(json);
    //if (checkResult.err) {
    //  debugLog(' [debug] invalid input:', checkResult.err);
    //  return {err: checkResult.err};
    //}
    //
    ////if (!redisClientDb1) redisClientDb1 = F.redisClientDb1;
    ////redisClientDb1.incr('logstash:count_old_way');
    //
    //// 更新实时兴趣点 mongo
    //__updateRtPoi(json).then(function (res) {
    //  debugLog(' [debug] updateRtPoi success');
    //  return __updateEsArticle(json);// 更新实时es内容
    //}).then(function (res) {
    //  debugLog(' [debug] ' + json.action + ' success');
    //  return __addLogToRedis(json);// 将日志送到redis
    //}, function (err) {
    //  debugLog(' [debug] ' + json.action + 'fail: ' + err);
    //  return __addLogToRedis(json);// 将日志送到redis
    //});
  } catch (ex) {
    debugLog(' [debug] logstash_error: ', ex);
  }
};

//
var logAnalyzer = require('./logAnalyzer.js');
Logstash.prototype.articleAuto = function (req, res) {
  try {
    if (typeof res === 'string') res = JSON.parse(res);
    debugLog(' [debug] request ' + JSON.stringify(req));
    debugLog(' [debug] response ' + JSON.stringify(res));

    var analyzeRes = logAnalyzer(req, res);
    if (analyzeRes.match && analyzeRes.succ) { //should save
      var json = analyzeRes.logstash;
      debugLog('[debug] logAnalyze_match', JSON.stringify(json));
      var checkResult = __checkInput(json);
      if (checkResult.err) {
        debugLog(' [debug] invalid input:', checkResult.err);
        return {err: checkResult.err};
      }
      __updateEsArticle(json).then(function (res) {
        debugLog(' [debug] ' + json.action + ' success:' + res);
      }, function (err) {
        debugLog(' [debug] ' + json.action + 'fail: ' + err);
      });
    } else if (analyzeRes.msg) {
      debugLog('[debug] logAnalyze_unmatch', analyzeRes.msg);
    } else {
      debugLog('[debug] logAnalyze_unmatch', JSON.stringify(analyzeRes));
    }
  } catch (ex) {
    debugLog(' [debug] logstash_error :' + ex);
  }
};

/**
 * TODO 添加多个
 * @param list
 */
Logstash.prototype.articleList = function* (list) {
  var result = yield articleDao.createMany(list);
  return {msg: 'done', result: result};

  //initFun();
  //for (let json of list) {
  //  let checkResult = __checkInput(json);
  //  if (checkResult.err) {
  //    debugLog('invalid input:', checkResult.err);
  //    //return {err: checkResult.err};
  //  }
  //  //yield __updateRtPoi(json);
  //  yield __updateEsArticle(json);
  //  //__addLogToRedis(json);
  //}
  //return {msg: 'done'};
};


var __checkArgs = {
  //  {"uid":1604,"vest":0,"tid":7851,"action":"post","articleContent":"为了你起得早","cid":32}
  post: ['uid', 'vest', 'tid', 'articleContent', 'cid'],
  view: ['tid'],
  like: ['tid'],
  reply: ['uid', 'tid'],
  edit: ['tid'], // articleContent or cid,如果cid修改，则标示人工分类
  //edit: ['uid', 'tid'], // articleContent or cid,如果cid修改，则标示人工分类
  'delete': ['uid', 'tid', 'vid'],
  status: ['tid']
};
/**
 * 检测输入参数 TODO
 * @param json
 * @private
 */
function __checkInput(json) {
  //debugLog('__checkInput');
  var ret = {};
  if (!json) ret.err = 'input must not be null or undefined';
  else if (!json.action) ret.err = 'must have json.action';
  else {
    let args = __checkArgs[json.action];
    if (!args) {
      ret.err = 'unsupport action,' + json.action;
    }
    for (let key of args) {
      if (json[key] === undefined) {
        ret.err = 'action ' + json.action + ' lost arg:' + key;
        break;
      }
    }
  }
  return ret;
}

/**
 * 每个操作对应的更新分数
 * @private
 */
var __score = {
  view: 1,
  like: 2,
  post: 3,
  'delete': 0.5,
  edit: 1.5,
  reply: 2
};
/**
 * 根据信息,更新 real time tag of interesting
 * @param json
 * @private
 */
function __updateRtPoi(json) {
  //debugLog('__updateRtPoi');
  //let obj = {
  //    uid: json.uid,
  //    cid2: json.cid2,
  //    value: __score[json.action]
  //};
  //return rtPoi.saveOne(obj);
  return Promise.resolve(json);
}

/**
 * 根据信息, 插入 or 更新 es中的发帖数据 post=发帖,read=阅读,praise=点赞,delete=删帖,edit=修改
 * @param json
 * @private
 */
function __updateEsArticle(json) {
  //debugLog('__updateEsArticle');
  var promise = null;
  if (json.action === 'post') {
    let cp = JSON.parse(JSON.stringify(json));
    // 'timeline', 'lastpost', 'views', 'liketimes', 'status', 'replies', 'userreplies'
    // 设置默认值
    let nowTime = new Date().getTime();
    cp.timeline = cp.timeline || nowTime;
    cp.lastpost = cp.lastpost || nowTime;
    cp.cid2 = cp.cid2 || -1;
    cp.views = cp.views || 0;
    cp.liketimes = cp.liketimes || 0;
    cp.status = typeof cp.status === 'undefined' ? 1 : cp.status;
    cp.replies = cp.replies || 0;
    cp.userreplies = cp.userreplies || 0;
    if (typeof cp.ctype === 'undefined') cp.ctype = 0;

    delete cp.action;
    promise = articleDao.createSingle(cp);
  } else if (json.action === 'delete') {
    promise = articleDao.falseDelete(json);
  } else if (json.action === 'edit') {
    promise = articleDao.updateArticle(json);
  } else if (json.action === 'reply') {
    promise = articleDao.updateReply(json);
  } else if (json.action === 'view') {
    promise = articleDao.increaseViews(json);
  } else if (json.action === 'like') {
    promise = articleDao.increaseLiketimes(json);
  } else if (json.action === 'status') {
    promise = articleDao.alterStatus(json);
  }

  return promise;
}

/**
 * 将数据存储到redis
 * @param json
 * @private
 */
function __addLogToRedis(json) {
  return "现阶段不执行，以后执行"; //  TODO

  //debugLog('__addLogToRedis');
  let redis = F.redisClient;
  let obj = {
    action: json.action,
    uid: json.uid,
    tid: json.tid,
    vestid: json.vestid
  };

  if (json.action === 'post' && json.action === 'edit') {
    obj.articleContent = json.articleContent;
  }

  redis.lpush([__redisKey, JSON.stringify(obj)], function (err, res) {
    if (err) debugLog('__addLogToRedis error:', err);
  });
}

var __redisKey = 'logstash:article';


